package v1

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

var upGrader = websocket.Upgrader{
	ReadBufferSize:  4096,
	WriteBufferSize: 4096,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func Ws(c *gin.Context) {
	//升级get请求为webSocket协议

	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Fatal("Upgrade", err)
		return
	}
	defer ws.Close()
	for {
		//读取ws中的数据
		mt, message, err := ws.ReadMessage()
		log.Printf("收到消息 %s", message)

		if err != nil {
			log.Fatal(err)
		}
		switch string(message) {
		case "ping":
			log.Printf("消息发送 %s", "pong")
			message = []byte("pong")
		default:
			//写入ws数据
			err = ws.WriteMessage(mt, message)
			if err != nil {
				log.Fatal(err)
			}
		}
	}
}
